<!--
《工艺规程管理》

- 仅列出根节点：parent_uuid = '0', queryParams.parentUuid: '0'
- 点击【详情】，新窗口打开

-->
<template>
  <div class="app-container">

    <!-- 检索条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="工艺编号" prop="docNum">
          <el-input
            v-model="queryParams.docNum"
            placeholder="请输入工艺编号模糊查询"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="itemName">
          <el-input
            v-model="queryParams.itemName"
            placeholder="请输入物料名称模糊查询"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="queryParams.dtRange"
            size="small"
            style="width: 250px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="物料编码" prop="itemNum">
          <el-input
            v-model="queryParams.itemNum"
            placeholder="请输入物料编码模糊查询"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            style="width: 250px"
          />
        </el-form-item>

        <el-form-item label="图纸号" prop="drawNum">
          <el-input
            v-model="queryParams.drawNum"
            placeholder="请输入图纸号模糊查询"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            style="width: 250px"
          />
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <!-- 批量操作 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:process:add']"
        >新增工艺
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table
      v-loading="loading"
      stripe
      :data="processList"
      :highlight-current-row="true"
      row-key="processUuid"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" fixed="left"/>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="备注：">
              <span>{{ scope.row.docNote }}</span>
            </el-form-item>
            <el-form-item label="审核人：">
              <span>{{ scope.row.confirmUserName }}</span>
            </el-form-item>
            <el-form-item label="审核结果：">
              <dict-tag :options="dict.type.oa_dict_confirm_status" :value="scope.row.oaDictConfirmStatus"/>
            </el-form-item>

            <el-form-item label="审核时间：">
              <span>{{ scope.row.confirmDt }}</span>
            </el-form-item>
            <el-form-item label="审核意见：">
              <span>{{ scope.row.confirmNote }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="物料名称" align="center"
                       prop="itemName" :show-overflow-tooltip="true" min-width="240"
                       v-if="columns[0].visible"/>
      <el-table-column label="物料编码" align="center"
                       prop="itemNum" width="160"
                       v-if="columns[1].visible"/>
      <el-table-column label="规格" align="center"
                       prop="itemSpecification" width="160"
                       v-if="columns[2].visible"/>
      <el-table-column label="零件号" align="center" prop="partNum" width="150" v-if="columns[3].visible"/>
      <el-table-column label="工艺编号" align="center" prop="docNum" width="150" v-if="columns[4].visible"/>
      <el-table-column label="版本号" align="center" prop="versionNum" width="60" v-if="columns[5].visible"/>
      <el-table-column label="图纸号" align="center" prop="drawNum" width="90" v-if="columns[6].visible"/>
      <el-table-column label="经办人" align="center"
                       prop="attentionUserName" width="120"
                       v-if="columns[7].visible"/>
      <el-table-column label="日期" align="center"
                       prop="docDt" width="150"
                       v-if="columns[8].visible"/>
      <el-table-column label="审核状态" align="center"
                       prop="oaDictConfirmStatus" width="120"
                       v-if="columns[9].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_dict_confirm_status" :value="scope.row.oaDictConfirmStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="submit_wait_confirm(scope.row)"
            v-hasPermi="['mes:process:details']"
          >提交待审
          </el-button>


          <el-button
            size="mini"
            type="text"
            icon="el-icon-set-up"
            @click="win_show_details(scope.row)"
            v-hasPermi="['mes:process:details']"
          >详情
          </el-button>

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
                       v-hasPermi="['mes:process:edit', 'mes:process:remove']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="showDialog_confirm" icon="el-icon-success"
                                v-hasPermi="['oa:confirm:edit']"
                                :disabled="scope.row.oaDictConfirmStatus !='waiting'">审核</el-dropdown-item>
              <el-dropdown-item command="handleDelete" icon="el-icon-delete"
                                v-hasPermi="['mes:process:remove']"
                                :disabled="scope.row.oaDictConfirmStatus !='editing'">删除
              </el-dropdown-item>

              <el-dropdown-item command="showDialog_copyProcess" icon="el-icon-copy-document"
                                v-hasPermi="['mes:process:remove']">拷贝该工艺规程
              </el-dropdown-item>

            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--

      对话框（1）：添加或修改工艺规程

      -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="650px" append-to-body :close-on-click-modal=false>
      <el-row :gutter="15">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">






        <el-row>
          <el-col :span="12">
            <el-input v-model="form.parentUuid" v-show="false"/>
            <el-form-item label="版本号" prop="versionNum">
              <el-input v-model="form.versionNum" :style="{width: '100%'}" placeholder="请输入版本号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图纸号" prop="drawNum">
              <el-input v-model="form.drawNum" :style="{width: '100%'}" placeholder="请输入图纸号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="物料" prop="fkItemUuid">
              <el-input v-model="form.fkItemUuid" placeholder="请输入物料表ID" v-show="false"/>

              <el-input placeholder="请选择物料" :style="{width: '100%'}" v-model="form.selectedItem" class="input-with-select">
                <el-button @click="dialog_show_selectItem()" slot="append" icon="el-icon-search"></el-button>
              </el-input>

            </el-form-item>
          </el-col>
          </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="零件号" prop="partNum">
              <el-input v-model="form.partNum" placeholder="请输入零件号"/>
            </el-form-item>
            <el-form-item label="单据时间" prop="docDt">
              <el-date-picker clearable size="small"
                              v-model="form.docDt"
                              type="datetime"
                              :style="{width: '100%'}"
                              value-format="yyyy-MM-dd HH:mm"
                              placeholder="选择单据时间">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="计量单位" prop="wmsDictMeasuringUnit">
              <el-select v-model="form.wmsDictMeasuringUnit" placeholder="请选择计量单位" :style="{width: '100%'}" disabled="true">
                <el-option
                  v-for="dict in dict.type.wms_dict_measuring_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>


          </el-col>

          <el-col :span="12">
            <el-form-item label="工艺编号" prop="docNum">
              <el-input v-model="form.docNum" :style="{width: '100%'}" placeholder="请输入编号"/>
            </el-form-item>
            <el-form-item label="数量" prop="processAmt">
              <el-input v-model="form.processAmt" placeholder="请输入数量" :style="{width: '100%'}"/>
            </el-form-item>

            <el-form-item label="经办人" prop="fkAttentionUserId">
              <el-input v-model="form.fkAttentionUserId" v-show="false"/>
              <el-input placeholder="请选择经办人" v-model="form.selectedAttentionUser" class="input-with-select">
                <el-button @click="dialog_show_selectUser" :style="{width: '100%'}" slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>




      </el-form>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.oaDictConfirmStatus != 'editing'">确 定</el-button>
        <el-button type="warning" @click="submitForm('waiting')" :disabled="form.oaDictConfirmStatus != 'editing'">提交待审
        </el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!--

      对话框（2）：生成生产任务 genTask

      -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title='dialog_title_genTask'
               :visible.sync="dialog_visible_genTask"
               width="800px" append-to-body :close-on-click-modal=false>
      <el-row style="margin-bottom: 15px;">
        <el-form ref="form_genTask" :model="form_genTask" :rules="rules_genTask"
                 label-width="90px">

          <el-input v-model="form_genTask.fkProcessUuid" v-show="false"/>

          <el-alert style="margin-bottom: 15px;"
            :title="form_genTask.latestTaskInfo"
            type="info">
          </el-alert>

          <el-col :span="24">
            <el-tooltip class="item" effect="dark" :content="form_genTask.tooltip_selectedOrderDetail" placement="top">
              <el-form-item label="订单明细" prop="selectedOrderDetail">
                <el-input v-model="form_genTask.fkOrderDetailUuid" v-show="false"/>
                <el-input placeholder="请选择订单明细" :style="{width: '100%'}" v-model="form_genTask.selectedOrderDetail"
                          class="input-with-select" readonly>
                  <el-button @click="dialog_show_selectOrderDetail" slot="append" icon="el-icon-search"></el-button>
                </el-input>
              </el-form-item>
            </el-tooltip>
          </el-col>

          <el-col :span="12">
            <el-form-item label="数量" prop="taskQty">
              <el-input-number v-model="form_genTask.taskQty" :style="{width: '100%'}" :step="2" placeholder="请输入数量"/>
            </el-form-item>
            <el-form-item label="标题" prop="docTitle">
              <el-input v-model="form_genTask.docTitle" :style="{width: '100%'}" placeholder="请输入标题"/>
            </el-form-item>
            <el-form-item prop="docDt">
              <span slot="label">
                <el-tooltip content="若使用当前时间请留空" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                时间
              </span>
              <el-date-picker
                v-model="form_genTask.docDt" type="datetime" placeholder="请选择单据时间"
                align="right" :style="{width: '100%'}" :picker-options="datetimePickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="计量单位" prop="wmsDictMeasuringUnit">
              <el-select v-model="form_genTask.wmsDictMeasuringUnit" placeholder="请选择计量单位" :style="{width: '100%'}">
                <el-option
                  v-for="dict in measuringUnitOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="docNum">
              <span slot="label">
                <el-tooltip content="生产任务编号" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                批次号
              </span>
              <el-input v-model="form_genTask.docNum" :style="{width: '100%'}" placeholder="请输入生产任务编号"/>
            </el-form-item>
            <el-form-item label="经办人" prop="fkAttentionUserId">
              <el-input v-model="form_genTask.fkAttentionUserId" v-show="false"/>
              <el-input placeholder="请选择经办人" :style="{width: '100%'}" v-model="form_genTask.selectedAttentionUserName"
                        class="input-with-select" readonly>
                <el-button @click="dialog_show_selectUser" slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="docNote">
              <el-input v-model="form_genTask.docNote" :style="{width: '100%'}" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>

        </el-form>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="submitForm_genTask" type="primary">确 定</el-button>
        <el-button @click="dialog_hide_genTask">取 消</el-button>
      </div>

    </el-dialog>


    <!--

      对话框（3）：拷贝工艺 copyProcess

      -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title='dialog_title_copyProcess'
               :visible.sync="dialog_visible_copyProcess" width="800px" append-to-body v-dialogDrag :close-on-click-modal=false>
      <el-row style="margin-bottom: 15px;">
        <el-form ref="form_copyProcess" :model="form_copyProcess" :rules="rules_copyProcess"
                 label-width="90px">

          <el-input v-model="form_copyProcess.processUuid" v-show="false"/>

          <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
            <div slot="header" class="clearfix">
              <b>源工艺信息</b>
            </div>
            <el-col :span="24">
              <el-form-item label="物料名称：" prop="itemName">
                {{form_copyProcess.itemName}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工艺编号：" prop="docNum">
                {{form_copyProcess.docNum}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本号：" prop="versionNum">
                {{form_copyProcess.versionNum}}
              </el-form-item>
            </el-col>
          </el-card>
          <el-col :span="24">
            <el-form-item label="新版本号" prop="versionNumNew">
              <el-input v-model="form_copyProcess.versionNumNew" :style="{width: '100%'}" placeholder="请输入新的版本号"/>
            </el-form-item>
          </el-col>

        </el-form>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="submitForm_copyProcess" type="primary">确 定</el-button>
        <el-button @click="dialog_hide_copyProcess">取 消</el-button>
      </div>

    </el-dialog>

    <select-user ref="component_selectAttentionUser" @ok="selectAttentionUser_done" />
    <select-item ref="component_selectItem" @ok="selectItem_done"/>
    <select-orderDetail ref="component_selectOrderDetail" @ok="selectOrderDetail_done"/>
    <confirm ref="component_confirm" :confirmParams="confirmParams" @ok="confirm_done"/>
  </div>
</template>

<script>
  import {listProcess, getProcess, delProcess, addProcess, updateProcess, copyProcess} from "@/api/mes/process";
  import {getLatestTaskByProcessUuid, genTask} from "@/api/mes/tasks";
  import {listWmsItems} from "@/api/wms/wmsItems";
  import {newDocNum} from "@/api/oa/docNum";
  import Treeselect from "@riophae/vue-treeselect";
  import selectUser from "../../comn/userGroup/selectUser";
  import selectItem from "../../wms/wmsItems/selectItem";
  import confirm from "../../oa/confirm";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import selectOrderDetail from "../../crm/crmOrders/selectOrderDetail";
  import { parseTime } from '@/utils/ruoyi'
  export default {
    name: "Process",
    dicts: ['oa_dict_confirm_status','wms_dict_measuring_unit'],
    components: {Treeselect, selectUser, selectItem, confirm, selectOrderDetail},
    data() {
      return {
        // 遮罩层
        loading: true,
        confirmParams: {},
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 工艺规程表格数据
        processList: [],
        // 工艺规程树选项
        processOptions: [],
        measuringUnitOptions:[],
        // 弹出层标题
        title: "",
        dialog_title_genTask: "",
        dialog_title_copyProcess: "",
        // 是否显示弹出层
        open: false,
        dialog_visible_genTask: false,
        dialog_visible_copyProcess: false,
        dialog_selectItem: {
          visible: false,
          title: "请选择物料",
          total: 0,
          itemList: [],
          queryParams: {
            itemName: null,
          }
        },
        // 查询参数
        queryParams: {
          parentUuid: '0',
          versionNum: null,
          drawNum: null,
          fkItemUuid: null,
          docNum: null,
          docDt: null,
          fkAttentionUserId: null,
        },
        // 表单参数
        form: {},
        form_copyProcess: {},
        form_genTask: {
          fkOrderDetailUuid: null,
          fkAttentionUserId: null,
          tooltip_selectedOrderDetail: null,
          latestTaskInfo: null,
        },
        // 表单校验
        rules: {
          drawNum: [
            {required: true, message: "请输入图纸号", trigger: "change"}
          ],
          versionNum: [
            {required: true, message: "请输入版本号", trigger: "change"}
          ],
          fkItemUuid: [
            {required: true, message: "请选择物料", trigger: "change"}
          ],

          docNum: [
            {required: true, message: "请输入工艺编号", trigger: "change"}
          ],
          docDt: [
            {required: true, message: "请选择单据时间", trigger: "change"}
          ],
          fkAttentionUserId: [
            {required: true, message: "请选择经办人", trigger: "change"}
          ],
        },
        // 表单校验
        rules_genTask: {
          taskUuid: [
            {required: true, message: "父ID不能为空", trigger: "blur"}
          ],
          fkOrderDetailUuid: [
            {required: true, message: "请选择订单明细", trigger: "change"}
          ],
          taskQty: [
            {required: true, message: "请输入数量", trigger: "change"}
          ],
          docTitle: [
            {required: true, message: "请输入标题", trigger: "change"}
          ],
          docDt: [
            {required: true, message: "请选择单据时间", trigger: "change"}
          ],
          wmsDictMeasuringUnit: [
            {required: true, message: "请选择计量单位", trigger: "change"}
          ],
          docNum: [
            {required: true, message: "请输入批次号", trigger: "change"}
          ],
          fkAttentionUserId: [
            {required: true, message: "请选择经办人", trigger: "change"}
          ],

        },
        // 表单校验
        rules_copyProcess: {
          versionNumNew: [
            {required: true, message: "请输入新的版本号", trigger: "change"}
          ],
        },
        // 列信息
        columns: [
          { key: 0, label: `物料名称`, visible: true },
          { key: 1, label: `物料编码`, visible: true },
          { key: 2, label: `规格`, visible: true },
          { key: 3, label: `零件号`, visible: true },
          { key: 4, label: `工艺编号`, visible: true },
          { key: 5, label: `版本号`, visible: true },
          { key: 6, label: `图纸号`, visible: true },
          { key: 7, label: `经办人`, visible: true },
          { key: 8, label: `日期`, visible: true },
          { key: 9, label: `审核状态`, visible: true }
        ],

        datetimePickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },

      };
    },
    created() {

      /**获取计量单位字典数据*/
      this.getDicts("wms_dict_measuring_unit").then(response => {
        this.measuringUnitOptions = response.data;
      });
      this.getList();
    },
    mounted() {
      // this.form.selectedItem_tooltip = '请选择物料'
    },
    methods: {

      /** 打开对话框：审核 */
      showDialog_confirm(row) {
        console.log(row)
        let obj = {
          tableName: 'mes_process',
          uuidColumn: 'process_uuid',
          fkUuid: row.processUuid,
          attentionUserNickName: row.attentionUserName,
          oaDictConfirmStatus:row.oaDictConfirmStatus,
          msg: `请审核工艺规程, 物料名称：${row.itemName},物料编号:${row.itemNum}`
        }
        this.$refs.component_confirm.showDialog_confirm(obj);
      },


      confirm_done() {
        this.getList()
      },

      /** 查询工艺规程列表 */
      getList() {
        this.loading = true;
        console.log( this.queryParams )
        if( this.queryParams.dtRange ){
          this.queryParams.dtRangeBegin = this.queryParams.dtRange[0]
          this.queryParams.dtRangeEnd = this.queryParams.dtRange[1]
        }else {
          this.queryParams.dtRangeBegin = null
          this.queryParams.dtRangeEnd = null
        }
        listProcess(this.queryParams).then(response => {
          response.rows.forEach(function (item, index) {
            item.isConfirmed = (!item.confirmDt) ? '未审核' : '已审核'
            item.taskQty = Math.floor(item.taskQty)
          })
          this.processList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      /** 转换工艺规程数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.processUuid,
          label: node.fkItemUuid,
          children: node.children
        };
      },

      /** 查询工艺规程下拉树结构 */
      getTreeselect() {
        listProcess().then(response => {
          this.processOptions = [];
          const data = {processUuid: 0, fkItemUuid: '顶级节点', children: []};
          data.children = this.handleTree(response.data, "processUuid", "parentUuid");
          this.processOptions.push(data);
        });
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },

      // 取消按钮 - 生成生产任务
      dialog_hide_genTask() {
        this.dialog_visible_genTask = false;
        this.reset();
      },

      // 表单重置
      reset() {
        this.form = {
          processUuid: null,
          parentUuid: null,
          versionNum: null,
          drawNum: null,
          fkItemUuid: null,
          docNum: null,
          processAmt: 1,
          docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
          fkAttentionUserId: null,
        };
        this.resetForm("form");
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.taskUuid)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },

      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        // this.getTreeselect();
        if (row != null && row.processUuid) {
          this.form.parentUuid = row.processUuid;
        } else {
          newDocNum({preCode:'PRO-', len: 12}).then(response => {
            this.form.docNum = response.msg
          })
        }
        this.form.oaDictConfirmStatus = 'editing'
        this.open = true;
        this.title = "添加工艺";
        this.form.selectedItem_tooltip = `请选择物料`
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        // this.getTreeselect();
        if (row != null) {
          this.form.parentUuid = row.processUuid;
        }
        getProcess(row.processUuid).then(response => {
          this.open = true;
          this.title = "修改工艺规程";

          this.form = response.data;

          this.form.selectedItem = `${this.form.itemName}（物料编码：${this.form.itemNum}）`
          // this.form.selectedItem_tooltip = `物料的唯一标识：${this.form.itemUuid}`

          this.form.selectedAttentionUser = `${this.form.attentionUserName}（ID：${this.form.fkAttentionUserId}）`
        });
      },

      submit_wait_confirm(row){
        this.form.oaDictConfirmStatus = 'waiting'
        this.form.processUuid = row.processUuid
        updateProcess(this.form).then(response => {
          this.$modal.msgSuccess("提交待审成功");
          this.getList();
        });

      },




      /** 提交按钮 */
      submitForm(confirmStatus) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            // this.form.parentUuid = '0'
            if(confirmStatus=='waiting') this.form.oaDictConfirmStatus = confirmStatus
            if (this.form.processUuid != null) {
              updateProcess(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addProcess(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },

      /** 提交按钮 - 生成生产任务 */
      submitForm_genTask() {
        this.$refs["form_genTask"].validate(valid => {
          if (valid) {
            // this.form.parentUuid = '0'
            if (this.form_genTask.processUuid != null) {
              updateProcess(this.form_genTask).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.dialog_visible_genTask = false;
                this.getList();
              });
            } else {
              genTask(this.form_genTask).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.dialog_visible_genTask = false;
                // this.getList();
              });
            }
          }
        });
      },


      /**

         1111111
        1::::::1
       1:::::::1
       111:::::1
          1::::1
          1::::1
          1::::1
          1::::1
          1::::1
          1::::1
          1::::1
          1::::1
       111::::::111
       1::::::::::1
       1::::::::::1
       111111111111

       ------------- copy process -------------

       */

      /** show dialog - copy process */
      showDialog_copyProcess(row) {
        this.form_copyProcess = row
        this.dialog_visible_copyProcess = true;
        this.dialog_title_copyProcess = "拷贝工艺规程"
      },

      /** hide dialog - copy process */
      dialog_hide_copyProcess() {
        this.dialog_visible_copyProcess = false;
        // this.reset();
      },

      /** submit form - copy process */
      submitForm_copyProcess() {
        this.$refs["form_copyProcess"].validate(valid => {
          if (valid) {
            // TODO 检测版本号是否已经存在，是否使用远程检测？
            console.log(this.form_copyProcess)
            this.form_copyProcess.versionNum = this.form_copyProcess.versionNumNew
          }
        });
      },


      /** 删除按钮操作 */
      handleDelete(row) {
        this.$modal.confirm(`是否确认删除物料：${row.itemName}（编号:${row.itemNum}）的工艺规程？`,'删除确认').then(function () {
          return delProcess(row.processUuid);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },

      /** 生成生产任务 */
      dialog_show_genTask(row) {

        this.form_genTask.latestTaskInfo = '💡 最近一次由该规程生成的生产任务 ... 查询中'

        getLatestTaskByProcessUuid(row.processUuid).then(response => {
          let d = response.data
          let m = '💡 最近一次由该规程生成的生产任务'
          if( d ){
            m = `${m}时间为：${d.docDt}，经办人：${ d.attentionUserName }`
          }else {
            m = `${m}：(未查询到相关数据)`
          }
          this.form_genTask.latestTaskInfo = m
        });

        this.form_genTask.fkProcessUuid = row.processUuid
        this.form_genTask.tooltip_selectedOrderDetail = '请选择一条订单中的明细'
        this.dialog_visible_genTask = true;
        this.dialog_title_genTask = "生成生产任务"
      },


      /**
       *  ------------- 选择物料 -------------
       * */


      /** 读取列表：物料 */
      getList_items() {
        this.loading = true;
        listWmsItems(this.dialog_selectItem.queryParams).then(response => {
          console.log(response)
          this.dialog_selectItem.itemList = response.rows;
          this.dialog_selectItem.total = response.total;
          this.loading = false;
        });
      },

      // 对话框：显示 - 选择物料
      // dialog_show_selectItem() {
      //   this.getList_items()
      //   this.form.selectedItem_tooltip = `请选择物料`
      //   this.dialog_selectItem.visible = true;
      //   this.dialog_selectItem.title = "选择物料";
      // },
      dialog_show_selectItem() {
        this.$refs.component_selectItem.dialog_show_selectItem();
      },

      // 完成：选择物料
      selectItem_done(item) {
        console.log(item)
        this.form.fkItemUuid = item.itemUuid
        this.form.selectedItem = `${item.itemName}（物料编码：${item.itemNum}）`
        this.form.wmsDictMeasuringUnit = item.wmsDictMeasuringUnit
        // this.form.selectedItem_tooltip = `物料的唯一标识：${item.itemUuid}`
      },


      /** 打开授权用户表弹窗 */
      dialog_show_selectUser() {
        this.$refs.component_selectAttentionUser.userGroup='technologist'
        this.$refs.component_selectAttentionUser.show();
      },

      /** 选择用户完成 */
      selectAttentionUser_done(user) {
        console.log(user)
        this.form.fkAttentionUserId = user.userId
        this.form.selectedAttentionUser = user.userNickNameAndId
        this.form_genTask.fkAttentionUserId = user.userId
        console.log(this.form_genTask.fkAttentionUserId)
        this.form_genTask.selectedAttentionUserName = `${user.nickName}（用户名：${user.userName}，ID：${user.userId}）`
        console.log(this.form_genTask.selectedAttentionUserName)

      },

      // 对话框：隐藏 - 选择物料
      dialog_hide_selectItem() {
        this.dialog_selectItem.visible = false;
      },

      // 窗口：显示 - 查看详情
      win_show_details(r) {
        this.$router.push(`/mes/process-details/${r.processUuid}`);
      },
      /** 显示对话框：选择订单 */
      dialog_show_selectOrderDetail() {
        this.$refs.component_selectOrderDetail.dialog_show_selectOrderDetail();
      },


      /** 选择订单明细完成 */
      selectOrderDetail_done(user) {
        this.form_genTask.fkOrderDetailUuid = user.row.orderDetailUuid;
        this.form_genTask.selectedOrderDetail =
          `物料名称：${user.row.itemName}，物料编码：${user.row.itemNum}，订单编号：${user.row.docNum}`;
        this.form_genTask.selectOrderDetail=
          `物料名称：${user.row.itemName}，
          物料编码：${user.row.itemNum}，
          订单编号：${user.row.docNum}`;
      },


      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleUpdate":
            this.handleUpdate(row);
            break;
          case "handleDelete":
            this.handleDelete(row);
            break;
          case "showDialog_confirm":
            this.showDialog_confirm(row);
            break;
          case "dialog_show_genTask":
            this.dialog_show_genTask(row);
            break;
          case "showDialog_copyProcess":
            this.showDialog_copyProcess(row);
            break;
          default:
            break;
        }
      },

    }
  };
</script>
